question about `static inline` functions in header files

  • Jump to comment-1
    zhjwpku@gmail.com2022-07-22T02:17:00+00:00
    I notice that there are lots of *static inline functions* in header files, the header file's content will go into each translation unit at preprocess phase, that means all the c file including the header will have a copy of the static inline function. The inline keyword is a hint for compiler to inline the function, if the compiler does inline the function, the definition could be optimized out by the compiler, but if the *inline function* can not be inlined, the function will reside in each of the translation units that include the header file, which means the same static function compiled multiple times and may waste some space? IMHO, the header files should only include the inline function's declaration, and the definition should be in c files. I am not sure why this kind of coding style came along, appreciate if some one can give me some clue, thanks :) -- Regards Junwang Zhao
    • Jump to comment-1
      tgl@sss.pgh.pa.us2022-07-22T03:03:43+00:00
      Junwang Zhao <zhjwpku@gmail.com> writes: > I notice that there are lots of *static inline functions* in header files, > the header file's content will go into each translation unit at preprocess > phase, that means all the c file including the header will have a copy > of the static inline function. We are assuming that the compiler will not emit unused static functions. This has been default behavior in gcc for ages. If you're unfortunate enough to have a compiler that won't do it, yes you're going to have a bloated binary. > IMHO, the header files should only include the inline function's declaration, > and the definition should be in c files. Then it couldn't be inlined, defeating the purpose. regards, tom lane
      • Jump to comment-1
        zhjwpku@gmail.com2022-07-22T03:08:54+00:00
        Ok, thanks for the clarification. On Fri, Jul 22, 2022 at 11:03 AM Tom Lane <tgl@sss.pgh.pa.us> wrote: > > Junwang Zhao <zhjwpku@gmail.com> writes: > > I notice that there are lots of *static inline functions* in header files, > > the header file's content will go into each translation unit at preprocess > > phase, that means all the c file including the header will have a copy > > of the static inline function. > > We are assuming that the compiler will not emit unused static functions. > This has been default behavior in gcc for ages. If you're unfortunate > enough to have a compiler that won't do it, yes you're going to have a > bloated binary. > > > IMHO, the header files should only include the inline function's declaration, > > and the definition should be in c files. > > Then it couldn't be inlined, defeating the purpose. > > regards, tom lane -- Regards Junwang Zhao